package com.tqjc.execute.step;

import com.tqjc.area.service.RollerService;
import com.tqjc.common.consts.NormalConst;
import com.tqjc.execute.cache.TaskStatus;
import com.tqjc.execute.cache.entity.WorkStatus;
import com.tqjc.execute.cache.service.CraneSteelCacheService;
import com.tqjc.execute.consts.WorkConst;
import com.tqjc.execute.exception.TaskRunningException;
import com.tqjc.execute.task.entity.Task;
import com.tqjc.execute.task.entity.TaskApart;
import com.tqjc.execute.task.service.impl.TaskApartServiceImpl;
import com.tqjc.execute.utils.DateUtils;
import com.tqjc.execute.utils.HttpPLCUtils;
import com.tqjc.execute.utils.PlcOperator;
import com.tqjc.execute.work.CraneWorkFactory;
import com.tqjc.execute.work.callback.TaskCallback;
import com.tqjc.plccontrol.service.PointInfoService;
import com.tqjc.system.core.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Description: 行走到位置吸取钢板步骤
 * 手动管理Bean的创建
 * @author: pzy
 * @date: 2023年05月18日 16:30
 */

@Slf4j
@Component
@Scope("prototype")
public class Move3Step extends TaskApart implements TaskCallback {

    @Resource
    PlcOperator plcOperator;

    @Resource
    RollerService rollerService;

    @Resource
    PointInfoService pointInfoService;

    @Resource
    CraneSteelCacheService craneSteelCacheService;

    @Resource
    CraneWorkFactory craneWorkFactory;
    @Resource
    TaskStatus taskStatus;

    @Value("${server_host}")
    private String serverHost;

    @Autowired
    private RestTemplate restTemplate;


    public Move3Step() {
        this.setType("move3");
    }


    @Override
    public void onPreExecute() {
        try {
            setBeginTime(new Date());
            //设置工作状态
            WorkStatus status = taskStatus.getWorkStatusByCraneType(getCraneType());
            status.setNowStep(getType());
            status.setNowSteelNum(getTask().getSteelNo());
            status.setUnnormalStatus("");
            taskStatus.setWorkStatusByCraneType(getCraneType(), status);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(getCraneType()+getType()+"前置出现异常",e);
        }


    }

    @Override
    public void onPostExecute() {
        try {
            setEndTime(new Date());

            //修改步骤状态
            WorkStatus status = taskStatus.getWorkStatusByCraneType(getCraneType());
            status.setNowStep("");
            status.setNowSteelNum("");
            taskStatus.setWorkStatusByCraneType(getCraneType(), status);

            //清除bean
            destroy();
        } catch (Exception e) {
            log.error(getCraneType()+getType()+"后置出现异常",e);
            e.printStackTrace();
        }

    }

    /**
     * create by: pzy
     * description: 根据任务生成步骤
     * create time: 2023/5/26 11:19
     *
     * @return void
     * @param: []
     */
    @Override
    public void setTaskApartByTask(Task task) {
        this.setCallback(this);
        super.setTaskApartByTask(task);
    }

    /**
     * @param :
     * @return void
     * @author Patienyon
     * @description 不同任务独有执行方式
     * @date 2023/6/19 9:13
     */
    @Override
    public void customAction() throws TaskRunningException {
        try {
            String craneType = this.getTask().getCraneType();

            //清所有任务标志
            if("offline".equalsIgnoreCase(getTask().getType())){
                HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.6.6",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","下料标志A",false);
                HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.6.7",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","下料标志B",false);
                HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.7",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","下料标志C",false);
                HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.7.1",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","下料标志D",false);
            }else if("online".equalsIgnoreCase(getTask().getType())){
                HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.6.2",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","上料标志A",false);
                HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.6.3",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","上料标志B",false);
                HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.6.4",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","上料标志C",false);
                HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.6.5",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","上料标志D",false);
            }
            //写入半自动标志
            HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.6.1",HttpPLCUtils.dataTypeList.get("bool"),"TRUE","半自动标志",false);

            //写入垛位
            if("offline".equalsIgnoreCase(getTask().getType())){
                String stockNo=craneWorkFactory.getCraneWorkImpl(craneType).getData().getStockNo();
                if("11C北".equals(craneType)){
                    if("1".equals(stockNo)){
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.8.7",HttpPLCUtils.dataTypeList.get("bool"),"TRUE","垛位1",false);
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.9",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","垛位2",false);
                    }else {
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.9",HttpPLCUtils.dataTypeList.get("bool"),"TRUE","垛位2",false);
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.8.7",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","垛位1",false);
                    }
                }else if("11C南".equals(craneType)){
                    if("1".equals(stockNo)){
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.8.7",HttpPLCUtils.dataTypeList.get("bool"),"TRUE","垛位1",false);
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.9",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","垛位2",false);

                    }else {
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.9",HttpPLCUtils.dataTypeList.get("bool"),"TRUE","垛位2",false);
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.8.7",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","垛位1",false);
                    }
                }
                else {
                    HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.8.7",HttpPLCUtils.dataTypeList.get("bool"),"TRUE","垛位1",false);
                }

            }
            //写入任务
            if("offline".equalsIgnoreCase(getTask().getType())){
                HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.7",HttpPLCUtils.dataTypeList.get("bool"),"TRUE","下料标志C",false);
            }else if("online".equalsIgnoreCase(getTask().getType())){
                HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.6.4",HttpPLCUtils.dataTypeList.get("bool"),"TRUE","上料标志C",false);
            }
            //写入任务启动
            HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.8.2",HttpPLCUtils.dataTypeList.get("bool"),"TRUE","任务启动",false);

            boolean isFinished = false;
            String isFinishStr="";
            Date startDate=new Date();
            while (!isFinished) {
                boolean overTime= DateUtils.isOverTimeByNow(startDate,100000);//超过100秒未完成，退出等待。
                if(overTime){
                    //log.error("等待{}天车半自动步骤3任务完成超时",getTask().getCraneType());
                    //throw new Exception("等待"+getTask().getCraneType()+"天车半自动步骤3任务完成超时");
                    WorkStatus status = taskStatus.getWorkStatusByCraneType(getCraneType());
                    status.setUnnormalStatus("等待任务完成超时");
                    taskStatus.setWorkStatusByCraneType(getCraneType(), status);
                    boolean isStartLogo= craneWorkFactory.getCraneWorkImpl(getCraneType()).getData().getSemiAutoRunFlag();
                    if(!isStartLogo){
                        break;
                    }
                }
                if("offline".equalsIgnoreCase(getTask().getType())){
                    isFinishStr= HttpPLCUtils.plcReadbc(restTemplate,serverHost,craneType,"下料C完成",false);
                }else if("online".equalsIgnoreCase(getTask().getType())){
                    isFinishStr= HttpPLCUtils.plcReadbc(restTemplate,serverHost,craneType,"上料C完成",false);
                }
                if ("true".equalsIgnoreCase(isFinishStr)) {
                    //清任务信号
                    if("offline".equalsIgnoreCase(getTask().getType())){
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.7",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","下料标志C",false);
                    }else if("online".equalsIgnoreCase(getTask().getType())){
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.6.4",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","上料标志C",false);
                    }
                    //清任务启动信号
                    HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.8.2",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","任务启动",false);
                    if("offline".equalsIgnoreCase(getTask().getType())){
                        //清下料C完成信号
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.8",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","下料C完成",false);
                    }else if("online".equalsIgnoreCase(getTask().getType())){
                        //清上料C完成信号
                        HttpPLCUtils.plcWritebcPlus(restTemplate,serverHost,craneType,"DB20.7.4",HttpPLCUtils.dataTypeList.get("bool"),"FALSE","上料C完成",false);
                    }
                    isFinished = true;
                    log.info("PLC反馈{}天车半自动步骤3任务完成",getTask().getCraneType());
                }
            }
            WorkStatus status = taskStatus.getWorkStatusByCraneType(getTask().getCraneType());
            status.setUnnormalStatus("");
            taskStatus.setWorkStatusByCraneType(getCraneType(), status);
        } catch (Exception e) {
            WorkStatus status = taskStatus.getWorkStatusByCraneType(getCraneType());
            status.setUnnormalStatus(e.getMessage());
            taskStatus.setWorkStatusByCraneType(getCraneType(), status);
            throw new TaskRunningException(e.getMessage(), getTask().getCraneType());
        }


    }

    /**
     * @param :
     * @return void
     * @author Patienyon
     * @description 销毁Bean
     * @date 2023-06-28 10:41
     */
    @Override
    public void destroy() throws Exception {

    }

    /**
     * @param :
     * @return void
     * @author Patienyon
     * @description 初始化Bean
     * @date 2023-06-28 10:41
     */
    @Override
    public void afterPropertiesSet() throws Exception {

    }
}


